package com.cskaoyan.catmall.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 布尔类型数据转换
 * 创建日期: 2022/01/11 18:46
 *
 * @author ghr
 */
@MappedTypes(Boolean.class)
@MappedJdbcTypes(JdbcType.DECIMAL)
public class BooleanTypeHandler implements TypeHandler<Boolean> {

    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        try {
            String value = objectMapper.writeValueAsString(aBoolean);
            //给对应序号的占位符提供值
            preparedStatement.setString(i, value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Boolean getResult(ResultSet resultSet, String s) throws SQLException {
        try {
            String result = resultSet.getString(s);
            Boolean aBoolean = objectMapper.readValue(result, Boolean.class);
            return aBoolean;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Boolean(false);
    }

    @Override
    public Boolean getResult(ResultSet resultSet, int i) throws SQLException {
        try {
            String result = resultSet.getString(i);
            Boolean aBoolean = objectMapper.readValue(result, Boolean.class);
            return aBoolean;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Boolean(false);
    }

    @Override
    public Boolean getResult(CallableStatement callableStatement, int i) throws SQLException {
        try {
            String result = callableStatement.getString(i);
            Boolean aBoolean = objectMapper.readValue(result, Boolean.class);
            return aBoolean;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Boolean(false);
    }
}